package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;
import com.itheima.pojo.PageResult;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;

    /*@Override
    public PageResult findAll(Integer page, Integer pageSize) {

       *//* //page 是页数
        Long total = empMapper.findTotal();
        //pageSize 是每页多少
        //rows 是第一页的数据
        Integer jump = (page - 1) * pageSize;
        List<Emp> rows = empMapper.findAll(jump, pageSize);
        //select * from emp
        return new PageResult(total, rows);*//*
        PageHelper.startPage(page, pageSize);
        Page<Emp> page1 = (Page<Emp>) empMapper.findPage();
        long total = page1.getTotal();
        List<Emp> rows = page1.getResult();
        return new PageResult(total,rows);
    }*/

    @Override
    public PageResult findAll(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {

        PageHelper.startPage(page, pageSize);
        Page<Emp> page1 = (Page<Emp>) empMapper.findPage(name, gender, begin, end);
        long total = page1.getTotal();
        List<Emp> rows = page1.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public void delete(List<Integer> ids) {
        empMapper.delete(ids);
        empExprMapper.delete(ids);
    }
@Transactional(rollbackFor = Exception.class )
    @Override
    public void add(Emp emp) {
    emp.setCreateTime(LocalDateTime.now());
    emp.setUpdateTime(LocalDateTime.now());
    emp.setPassword("123456");
        empMapper.add(emp);
        List<EmpExpr> empExpr = emp.getExprList();
        if (empExpr != null && empExpr.size() > 0) {
            for (EmpExpr expr : empExpr) {
                expr.setEmpId(emp.getId());
            }
            empExprMapper.add(emp.getExprList());
        }

    }

}
